// controllers/productController.js
const { pool } = require('../config/db');

// 1. 获取商品列表（普通用户可看，积分兑换页展示）
exports.getProductList = async (req, res, next) => {
  try {
    const { page = 1, limit = 10, sort = 'point_price' } = req.query; // 支持按积分价格排序
    const offset = (page - 1) * limit;

    // 验证排序字段（避免SQL注入，只允许按指定字段排序）
    const validSortFields = ['point_price', 'stock', 'created_at', 'name'];
    const sortField = validSortFields.includes(sort) ? sort : 'point_price';

    // 查询商品列表（只显示库存>0的商品，避免用户兑换无库存商品）
    const [products] = await pool.query(
      `SELECT id, name, point_price, stock, image_url, description, created_at 
       FROM goods 
       WHERE stock > 0 
       ORDER BY ${sortField} ASC 
       LIMIT ? OFFSET ?`,
      [parseInt(limit), parseInt(offset)]
    );

    // 查询商品总数（用于分页）
    const [countResult] = await pool.query(
      'SELECT COUNT(*) as total FROM goods WHERE stock > 0'
    );
    const total = parseInt(countResult[0].total);

    res.status(200).json({
      success: true,
      count: products.length,
      total,
      totalPages: Math.ceil(total / limit),
      currentPage: parseInt(page),
      data: products
    });
  } catch (err) {
    next(err);
  }
};

// 2. 获取单个商品详情（用户兑换前查看商品详情）
exports.getProductDetail = async (req, res, next) => {
  try {
    const { id } = req.params;

    const [products] = await pool.query(
      `SELECT id, name, point_price, stock, image_url, description, created_at, updated_at 
       FROM goods 
       WHERE id = ?`,
      [id]
    );

    if (products.length === 0) {
      const error = new Error('商品不存在或已下架');
      error.statusCode = 404;
      throw error;
    }

    res.status(200).json({
      success: true,
      data: products[0]
    });
  } catch (err) {
    next(err);
  }
};

// 3. 创建商品（管理员功能）
exports.createProduct = async (req, res, next) => {
  try {
    const { name, point_price, stock, image_url, description } = req.body;

    // 验证必填字段（商品名称、积分价格、库存必传）
    if (!name || !point_price || stock === undefined) {
      const error = new Error('商品名称、积分价格、库存为必填项');
      error.statusCode = 400;
      throw error;
    }

    // 验证积分价格和库存为正数
    if (parseInt(point_price) <= 0 || parseInt(stock) < 0) {
      const error = new Error('积分价格必须为正数，库存不能为负数');
      error.statusCode = 400;
      throw error;
    }

    // 检查商品名称是否重复
    const [nameExists] = await pool.query(
      'SELECT id FROM goods WHERE name = ?',
      [name]
    );
    if (nameExists.length > 0) {
      const error = new Error('该商品名称已存在');
      error.statusCode = 400;
      throw error;
    }

    // 插入商品数据
    const [result] = await pool.query(
      `INSERT INTO goods 
       (name, point_price, stock, image_url, description, created_at, updated_at) 
       VALUES (?, ?, ?, ?, ?, NOW(), NOW())`,
      [name, parseInt(point_price), parseInt(stock), image_url || '', description || '']
    );

    // 获取新创建的商品
    const [newProduct] = await pool.query(
      'SELECT * FROM goods WHERE id = ?',
      [result.insertId]
    );

    res.status(201).json({
      success: true,
      message: '商品创建成功',
      data: newProduct[0]
    });
  } catch (err) {
    next(err);
  }
};

// 4. 更新商品（管理员功能）
exports.updateProduct = async (req, res, next) => {
  try {
    const { id } = req.params;
    const { name, point_price, stock, image_url, description } = req.body;

    // 1. 检查商品是否存在
    const [productExists] = await pool.query(
      'SELECT id FROM goods WHERE id = ?',
      [id]
    );
    if (productExists.length === 0) {
      const error = new Error('商品不存在');
      error.statusCode = 404;
      throw error;
    }

    // 2. 构建更新字段（只更新传了的值）
    const updateFields = [];
    const values = [];
    if (name) {
      // 若更新名称，检查新名称是否重复
      const [nameExists] = await pool.query(
        'SELECT id FROM goods WHERE name = ? AND id != ?',
        [name, id]
      );
      if (nameExists.length > 0) {
        const error = new Error('该商品名称已存在');
        error.statusCode = 400;
        throw error;
      }
      updateFields.push('name = ?');
      values.push(name);
    }
    if (point_price !== undefined) {
      if (parseInt(point_price) <= 0) {
        const error = new Error('积分价格必须为正数');
        error.statusCode = 400;
        throw error;
      }
      updateFields.push('point_price = ?');
      values.push(parseInt(point_price));
    }
    if (stock !== undefined) {
      if (parseInt(stock) < 0) {
        const error = new Error('库存不能为负数');
        error.statusCode = 400;
        throw error;
      }
      updateFields.push('stock = ?');
      values.push(parseInt(stock));
    }
    if (image_url !== undefined) {
      updateFields.push('image_url = ?');
      values.push(image_url);
    }
    if (description !== undefined) {
      updateFields.push('description = ?');
      values.push(description);
    }

    // 没有要更新的字段
    if (updateFields.length === 0) {
      const error = new Error('请提供要更新的字段（名称/积分价格/库存/图片/描述）');
      error.statusCode = 400;
      throw error;
    }

    // 添加更新时间
    updateFields.push('updated_at = NOW()');
    values.push(id); // 最后一个参数是商品ID（WHERE条件）

    // 3. 执行更新
    await pool.query(
      `UPDATE goods SET ${updateFields.join(', ')} WHERE id = ?`,
      values
    );

    // 4. 获取更新后的商品
    const [updatedProduct] = await pool.query(
      'SELECT * FROM goods WHERE id = ?',
      [id]
    );

    res.status(200).json({
      success: true,
      message: '商品更新成功',
      data: updatedProduct[0]
    });
  } catch (err) {
    next(err);
  }
};

// 5. 删除商品（管理员功能）
exports.deleteProduct = async (req, res, next) => {
  try {
    const { id } = req.params;

    // 1. 检查商品是否存在
    const [productExists] = await pool.query(
      'SELECT id FROM goods WHERE id = ?',
      [id]
    );
    if (productExists.length === 0) {
      const error = new Error('商品不存在');
      error.statusCode = 404;
      throw error;
    }

    // 2. 执行删除（也可改为“软删除”，添加 is_deleted 字段，避免误删数据）
    await pool.query('DELETE FROM goods WHERE id = ?', [id]);

    res.status(200).json({
      success: true,
      message: '商品删除成功',
      data: {}
    });
  } catch (err) {
    next(err);
  }
};